package com.grom.dao;

import java.util.List;

import com.grom.po.Brand;
import com.grom.po.BrandVisitHistory;
import com.grom.po.ContactInfo;
import com.grom.util.IDCreator;
import com.holder.DBContextHolder;
import com.holder.DBUTil;

class BrandDaoImpl implements BrandDao {

	public List<Brand> getAllBrands() {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		List<Brand> result = DBUTil.select(Brand.class);
		return result;
	}

	public void add(Brand brand, List<ContactInfo> conList, List<BrandVisitHistory> historyList) {
		brand.setID(IDCreator.getSingleId());
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		DBUTil.save(brand);
		if (conList == null || conList.size() == 0) {
			return;
		}
		for (ContactInfo info : conList) {
			info.setRelatedId(brand.getID());
			DBUTil.save(info);
		}
		if (historyList == null || historyList.size() == 0) {
			return;
		}
		for (BrandVisitHistory his : historyList) {
			his.setBrandId(brand.getID());
			DBUTil.save(his);
		}
	}

	public void update(Brand brand, List<ContactInfo> conList, List<BrandVisitHistory> historyList) {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		DBUTil.update(brand);
		String sql = "delete from contactinfo where relatedId ='" + brand.getID() + "'";
		DBUTil.update(sql);
		if (conList == null || conList.size() == 0) {
			return;
		}
		for (ContactInfo info : conList) {
			info.setRelatedId(brand.getID());
			DBUTil.save(info);
		}
		sql = "delete from brandvisithistory where brandid ='" + brand.getID() + "'";
		DBUTil.update(sql);
		if (historyList == null || historyList.size() == 0) {
			return;
		}
		for (BrandVisitHistory his : historyList) {
			his.setBrandId(brand.getID());
			DBUTil.save(his);
		}
	}

	public Brand getBrandById(String ID) {
		String sql = "select * from brand where id = '" + ID + "'";
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		List<Brand> result = DBUTil.getResult(sql, Brand.class);
		return result.get(0);
	}

	public void delete(Brand brand) {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		DBUTil.delete(brand);
	}

	public List<Brand> selectByCondition(String sql) {
		DBContextHolder.setContextConnection(DatabaseDao.getConnection());
		List<Brand> result = DBUTil.getResult(sql, Brand.class);
		return result;
	}

}
